<template>
  <page-card title="机构管理"
             sub-title="编辑"
             :need-back="true">
    <a-row type="flex"
           justify="center">
      <!-- 角色信息 -->
      <a-col v-if="extendData.length>0"
             :span="24">
        <a-divider orientation="left">
          基本信息
        </a-divider>
      </a-col>
      <a-col :span="24">
        <a-form-model ref="form"
                      :model="form"
                      :rules="rules"
                      :label-col="{ span: 6 }"
                      :wrapper-col="{ span: 12 }">
          <a-form-model-item v-if="form.parentId!=0 && form.parentId!=null"
                             label="父级机构"
                             prop="parentId">
            <a-input type="hidden"
                     v-model="form.parentId" />
            <a-input type="hidden"
                     v-model="form.levelCode" />
            <span v-text="form.parentName"></span>
          </a-form-model-item>

          <a-form-model-item label="机构简称："
                             prop="name">
            <a-input placeholder="机构简称长度不超过30位"
                     :maxLength="30"
                     v-model="form.name"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="机构全称："
                             prop="fullName">
            <a-input disabled
                     placeholder="机构全称长度不超过30位"
                     :maxLength="30"
                     v-model="form.fullName"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="机构类型："
                             prop="type">
            <a-radio-group :disabled="form.isTest == '1' || id ? true : false"
                           name="radioGroup"
                           v-model="form.type">
              <a-radio value="1">分类</a-radio>
              <a-radio v-if="form.parentId == 0 || form.parentType == 1 || form.parentType == 2"
                       value="2">单位（企业）</a-radio>
              <a-radio v-if="form.parentType == 2 || form.parentType == 3"
                       value="3">内部机构</a-radio>
            </a-radio-group>
          </a-form-model-item>

          <a-form-model-item label="是否为测试机构"
                             help="部署生产环境的测试机构，用于环境测试，与正式数据完全隔离"
                             prop="isTest">
            <ZSwitchOneZero disabled
                            checked-children="是"
                            un-checked-children="否"
                            v-model="form.isTest" />
          </a-form-model-item>

          <a-form-model-item label="排序号："
                             prop="orderNo">
            <a-input-number placeholder="正整数字排序号"
                            v-model="form.orderNo"
                            :min="1"
                            :max="1000000"
                            allow-clear />
          </a-form-model-item>
          <a-form-model-item label="机构编码："
                             prop="code">
            <a-input disabled
                     v-model="form.code"
                     placeholder="机构唯一编码，长度不超过50位"
                     :maxLength="50"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="标签："
                             prop="label">
            <a-input v-model="form.label"
                     placeholder="请输入标签"
                     :maxLength="100"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="是否隐藏："
                             prop="isHide">
            <z-switch-one-zero checked-children="是"
                               un-checked-children="否"
                               v-model="form.isHide" />
          </a-form-model-item>
          <a-form-model-item label="是否启用："
                             prop="state">
            <z-switch-one-zero checked-children="是"
                               un-checked-children="否"
                               @change="onChangeState"
                               v-model="form.state" />
          </a-form-model-item>
          <a-form-model-item label="联系电话："
                             prop="tel">
            <a-input placeholder="联系电话可以是短号、电话、手机号，长度不超过20位"
                     v-model="form.tel"
                     :maxLength="20"
                     allow-clear />
          </a-form-model-item>
          <a-form-model-item label="单位地址："
                             prop="unitAddress">
            <a-input placeholder="单位地址，长度不超过100位"
                     v-model="form.unitAddress"
                     :maxLength="100"
                     allow-clear />
          </a-form-model-item>

          <a-form-model-item label="机构OPENID："
                             prop="openId">
            <a-input placeholder="机构开放平台ID"
                     v-model="form.openId"
                     disabled />
          </a-form-model-item>
          <a-form-model-item label="备注："
                             class="unit-edit-form-item-textarea">
            <a-textarea placeholder="机构信息备注说明，长度不超过200位"
                        :rows="3"
                        v-model="form.unitnote"
                        :maxLength="200"
                        allow-clear />
          </a-form-model-item>
          <a-col v-if="extendData.length>0"
                 :span="24">
            <a-divider orientation="left">
              扩展信息
            </a-divider>
          </a-col>
          <a-form-model-item v-for="item in extendData"
                             :key="item.id"
                             :label="item.columnsName"
                             :prop="item.columnsValue">

            <!-- 文本框 -->
            <a-input allowClear
                     :disabled="item.isUpdate == 0"
                     v-if="item.columnsType == 1"
                     :placeholder="'请输入'+item.columnsName"
                     v-model="form[item.columnsValue]" />
            <!-- 下拉框 -->
            <a-select allowClear
                      :disabled="item.isUpdate == 0"
                      v-if="item.columnsType == 2"
                      :placeholder="'请选择'+item.columnsName"
                      v-model="form[item.columnsValue]">
              <a-select-option v-for="(itemSelect,index) in item.source"
                               :value="itemSelect.value"
                               :key="index">
                {{ itemSelect.label }}
              </a-select-option>
            </a-select>
            <!-- 单选框 -->
            <a-radio-group v-if="item.columnsType == 3"
                           :disabled="item.isUpdate == 0"
                           :options="item.source"
                           v-model="form[item.columnsValue]"
                           :default-value="radioDefault(item.source)" />
            <!-- 时间组件 -->
            <a-date-picker v-if="item.columnsType == 4"
                           :disabled="item.isUpdate == 0"
                           v-model="form[item.columnsValue]"
                           style="width:100%"
                           show-time
                           :format="item.source.format" />
          </a-form-model-item>

          <a-form-model-item label=" "
                             :colon="false">
            <div style="text-align:center">
              <a-space size="small">
                <a-button @click="delUnit"
                          style="width: 80px;">删除</a-button>
                <a-button type="primary"
                          @click="save"
                          style="width: 80px;">保存</a-button>
              </a-space>
            </div>
          </a-form-model-item>
        </a-form-model>
      </a-col>
    </a-row>
  </page-card>
</template>

<script>
import { del, getById, saveOrUpdate, startAndStopState } from '../../api/unit/index'
import { getNoCacheCodeListByCode } from '../../api/dictionary'

export default {
  data () {
    return {
      id: this.$route.query?.id || '',
      statusLoading: false,
      syncOff: false,
      extendData: [],
      syncVisible: false,
      mediaType: '1',
      syncType: '',
      mediaId: '',
      deptId: '',
      subTitle: '',
      themeList: [],
      status: true,
      form: {
        id: '',
        name: '',
        fullName: '',
        parentId: 0,
        actual: '1',
        code: '',
        orderNo: '',
        levelCode: '',
        state: '1',
        type: '1',
        openId: '1',
        otherSysId: '1',
        url: '',
        zwddId: '',
        contact: '',
        unitAddress: '',
        tel: '',
        theme: '',
        unitnote: '',
        isTest: '0',
        isHide: '0',
        label: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入机构简称' },
          { max: 100, message: '机构简称长度不超过100位' }
        ],
        tel: [
          { pattern: /^([0|1|2|3|4|5|7|8|9]\d{2,10})$/, message: '联系电话格式不正确' }
        ],
        fullName: [
          { required: true, message: '请输入机构全称' },
          { max: 100, message: '机构全称长度不超过100位' }
        ],
        contact: [
          { min: 2, max: 30, message: '联系人姓名长度最少2位，不超过20位' }
        ],
        orderNo: [
          { required: true, message: '请输入排序号' },
          { pattern: /^[1-9]\d*$/, message: '排序号应该为正整数' }
        ],
        type: [
          {
            required: true,
            message: '请选择机构类型'
          }
        ]
      }
    }
  },
  created () {
    // this.loadTheme()
  },
  mounted () {
    this.load()
  },
  methods: {
    /**
     * 单选框默认值判断
     */
    radioDefault (list) {
      for (let i in list) {
        if (list[i].default) {
          return list[i].value
        }
      }
    },
    /**
     * 加载主题类型
     */
    loadTheme () {
      getNoCacheCodeListByCode({ code: 'THEME' }).then(res => {
        this.themeList = res
      })
    },
    /**
     * 根据id参数 判断新增还是修改
     */
    load () {
      const id = this.$route.query.id
      if (!id) {
        this.message.error('非法请求')
        return
      }
      getById(id).then(res => {
        this.form = res
        this.extendData = res.sysUnitExtendData
        this.extendData.forEach((item) => {
          if (item.columnsType == 2) {
            if (this.form[item.columnsValue] == '[]' || this.form[item.columnsValue] == null) {
              this.form[item.columnsValue] = []
            }
          }
          if (item.columnsType == 3 && !this.form[item.columnsValue]) {
            let list = JSON.parse(item.source)
            for (let i in list) {
              if (list[i].default) {
                this.form[item.columnsValue] = list[i].value
              }
            }
          }

          if (item.columnsType == 1 && item.isNull == 1) {
            this.rules[item.columnsValue] = [{
              required: true,
              message: '请输入' + item.columnsName
            }]
          }
          if (item.columnsType == 2 || item.columnsType == 3 || item.columnsType == 4) {
            item.source = JSON.parse(item.source)
            if (item.isNull == 1) {
              this.rules[item.columnsValue] = [{
                required: true,
                message: '请选择' + item.columnsName
              }]
            }
          }
        })
      })
    },

    onChangeState (value) {
      if (!this.statusLoading) {
        this.statusLoading = true
        const checked = value === '1'
        const stopName = checked ? '启用' : '停用'
        startAndStopState(checked, this.form.id).then((res) => {
          this.message.info(stopName + '成功')
        }).catch(() => {
          this.form.state = !checked ? '1' : '0'
        }).finally(() => {
          this.statusLoading = false
        })
      }
    },

    /**
     * 保存
     */
    save () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          /**
           * 处理扩展字段
           */
          for (let i in this.form.sysUnitExtendData) {
            let sourceList = this.form.sysUnitExtendData[i].source
            for (let key in this.form) {
              if (this.form.sysUnitExtendData[i].columnsValue == key) {
                for (let j in sourceList) {
                  if (this.form[key] == sourceList[j].value) {
                    this.form.sysUnitExtendData[i].extendKey = sourceList[j].label
                  }
                }
                this.form.sysUnitExtendData[i].extendValue = this.form[key]
                break
              }
            }
          }
          saveOrUpdate(this.form).then(res => {
            this.$router.back()
          })
        }
      })
    },
    delUnit () {
      const me = this
      me.confirm({
        content: '确定删除机构吗？',
        okText: '确认',
        cancelText: '取消',
        onOk () {
          del(me.form.id).then(res => {
            me.$router.back()
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.btn {
  width: 80px;
  margin: 0px 50px;
}

.x-row {
  border: 0px solid #d9d9d9;
}
::v-deep .unit-edit-form-item-textarea .ant-input-affix-wrapper {
  height: 150px;
  background: red;
}
::v-deep .unit-edit-form-item-textarea .ant-input-affix-wrapper .ant-input {
  height: 100% !important;
}
</style>
